package com.oauth2;

import com.entity.UserEntity;
import com.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Set;

/**
 * 认证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
@Slf4j
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     * 此方法用于在用户登录后，获取该用户的权限信息，以便进行权限验证。
     *
     * @param principals 用户的主体信息集合，包含登录时验证的用户信息。
     * @return 返回一个AuthorizationInfo对象，包含用户的所有权限信息。
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 从主体信息中获取当前登录的用户对象
        UserEntity user = (UserEntity) principals.getPrimaryPrincipal();
        String userId = String.valueOf(user.getId());

        // 通过用户ID，查询用户拥有的所有权限
        String permsSet = userService.getUserPermissions(userId);
        // 创建并设置权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(Collections.singleton(permsSet));
        return info;
    }


    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        UserEntity tokenEntity = userService.queryByToken(accessToken);
        //token失效
        if (tokenEntity == null || tokenEntity.getExpiratedtime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        //查询用户信息
        UserEntity user = userService.queryUser(Long.valueOf(tokenEntity.getUserId()));
        //账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        return new SimpleAuthenticationInfo(user, accessToken, getName());
    }
}
